#include <signal.h>
#include <vector>
#include <unistd.h>
#include <unordered_map>
#include <iostream>
#include "xLog.h"
#include "../3rd/inih/cpp/INIReader.h"
#include "xUtil.h"
#include "LoginService.h"
#include "xLog.h"
bool             g_daemon = false;
std::string      g_server_addr;
uint16_t         g_server_port;
uint32_t         g_server_id;
std::string      g_server_version;
std::string      g_log_path;


void OnHandle(int sid)
{
    std::cout << "login server end" << std::endl;
    LoginService::GetInstance()->Finish();
}
void HookSignals()
{
	signal(SIGINT, OnHandle);
	signal(SIGQUIT, OnHandle);
	signal(SIGTERM, OnHandle);
	signal(SIGABRT, OnHandle);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGUSR1, OnHandle);
}
void UnHookSignals()
{
	signal(SIGINT, 0);
	signal(SIGQUIT, 0);
	signal(SIGTERM, 0);
	signal(SIGABRT, 0);
	signal(SIGUSR1, 0);
}
bool InitConfig(INIReader& reader)
{
    if(reader.ParseError() < 0)
    {
        XLOG_ERROR("Can't load loginserver");
        return false;
    }
    //server 
    g_server_addr = reader.GetString("server","bind_ip","127.0.0.1");
    g_server_port = reader.GetInteger("server","port",7777);
    g_server_version = reader.GetString("server","version","1");

    //config
    g_log_path = reader.GetString("config","log_path","./service_log");

    return true;
}

bool InitSystem()
{
    return true;
}

int main(int argc,char** argv)
{
    INIReader reader("../../ini/loginserver.ini");

    if(!InitConfig(reader))
    {
        return 0;
    }

    if(g_daemon)
    {
        XUtil::DaemonInit();
    }
    
    HookSignals();

    if(!InitSystem())
        return -1;

    if(!XUtil::CreatePidFile())
    {
        return -1;
    }

    LoginService::GetInstance()->Main();

    UnHookSignals();
    return 0;
}
